//
//  GasViewController.m
//  FuelLog
//
//  Created by Pure Mass Communications on 9/1/08.
//  Copyright 2008 . All rights reserved.
//
//  Placed under GPL v2 with the kind permission of Pure Mass Communications
//
//  Modified to make compile under SDK 3.1 by Olaf Greck in May 2010
//
//
//  This program is free software; you can redistribute it and/or
//  modify it under the terms of the GNU General Public License
//  as published by the Free Software Foundation; either version 2
//  of the License, or (at your option) any later version.

//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.

//  You should have received a copy of the GNU General Public License
//  along with this program; if not, write to the Free Software
//  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

#import "DateViewController.h"
#import "FuelLogAppDelegate.h"
#import "FuelLogViewController.h"
#import "GasViewController.h"




@implementation GasViewController

@synthesize gas, navItem; 
@synthesize dateButton, deleteButton;
@synthesize odometerBox, fuelLabel, fuelBox, costBox, unitCostText, fullTankSwitch;
@synthesize versionLabel;

- (void)reallyDelete {
	if (gas.pk != -1) {
		FuelLogAppDelegate *appDelegate = (FuelLogAppDelegate *)[[UIApplication sharedApplication] delegate];
		[appDelegate removeGas:gas];
	}
	[self cancel:nil];
}

#pragma mark UIAlertView

- (void)alertDeleteCancelAction
{
	// open a alert with an OK and cancel button
	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"Delete this entry?"
												   delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Yes, Delete", nil];
	[alert show];
	[alert release];
}

#pragma mark UIAlertViewDelegate

- (void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)buttonIndex
{
	if (buttonIndex == [alert cancelButtonIndex]) {
		return;
	}
	[self reallyDelete];
}

#pragma mark UIViewController

- (void)setGas:(Gas *)anotherGas {
	[gas release];
	gas = anotherGas;
	[gas retain];
	[self setDateValue:gas.date];
}

- (NSDate *)dateValue {
	return dateValue;
}

- (void)setDateValue:(NSDate *)anotherDate {
	[dateValue release];
	dateValue = anotherDate;
	[dateValue retain];
	NSDateFormatter *formatter = [FuelLogAppDelegate pref].dateFormatter;
	NSString *title = [formatter stringFromDate:dateValue];
	[dateButton setTitle:title forState:UIControlStateNormal];
	[dateButton setTitle:title forState:UIControlStateHighlighted];
	[dateButton setTitle:title forState:UIControlStateSelected];
}

/*
// override if customizing
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
	if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
		// Initialization code
	}
	return self;
}
*/
 
/*
 Implement loadView if you want to create a view hierarchy programmatically
- (void)loadView {
}
 */

- (void)viewDidLoad { 
    [super viewDidLoad]; 
	odometerBox.clearButtonMode = UITextFieldViewModeWhileEditing;
	fuelBox.clearButtonMode = UITextFieldViewModeWhileEditing;
	costBox.clearButtonMode = UITextFieldViewModeWhileEditing;
	[self.dateButton useSystemTouchStyle]; 
	[self.deleteButton useRedDeleteStyle]; 
	
}

	
- (void)viewWillAppear:(BOOL)animated {
	[super viewWillAppear:animated];
	[self setBoxes];
}

	
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
	// Return YES for supported orientations
	return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


- (void)didReceiveMemoryWarning {
	[super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
	// Release anything that's not essential, such as cached data
}


- (void)dealloc {
	[gas release];
	[dateButton release];
	[odometerBox release];
	[fuelLabel release];
	[fuelBox release];
	[dpfLabel release];
	[dpfText release];
	[costBox release];
	[unitCostText release];
	[deleteButton release];
	[fullTankSwitch release];
	[dateValue release];
	[versionLabel release];
	[super dealloc];
}

#pragma mark -


- (IBAction)done:(id)sender {
	[odometerBox resignFirstResponder];
	[fuelBox resignFirstResponder];
	[costBox resignFirstResponder];
	float distance = [FuelLogAppDelegate scanFloat:odometerBox.text];
	float fuel = [FuelLogAppDelegate scanFloat:fuelBox.text];
	float cost = [FuelLogAppDelegate scanFloat:costBox.text];
	if (distance <= 0) {
		[errorText setText:(NSLocalizedString(@"GasView Odometer",@"Odometer must be a positive number.")) ];
		return;
	}
	if (fuel <= 0) {
		[errorText setText:(NSLocalizedString(@"GasView Fuel",@"Fuel volume must be a positive number.")) ];
		return;
	}
	if (cost < 0) {
		[errorText setText:(NSLocalizedString(@"GasView Cost",@"Cost must be a positive number.")) ];
		return;
	}
	FuelLogAppDelegate *appDelegate = (FuelLogAppDelegate *)[[UIApplication sharedApplication] delegate];
	Gas *lastPump = [appDelegate findPreviousGasEntry:dateValue odometer:distance];
	if (lastPump && (gas.pk == -1 || gas.pk != lastPump.pk)) {
		if (distance < lastPump.odometer) {
			[errorText setText:[NSString stringWithFormat:@"Odometer is lower than previous value of %.1f", lastPump.odometer]];
			return;
		} else if ([dateValue compare:lastPump.date] == NSOrderedAscending) {
			NSDateFormatter *formatter = [FuelLogAppDelegate pref].dateFormatter;
			NSString *lastDate = [formatter stringFromDate:lastPump.date];			
			[errorText setText:[NSString stringWithFormat:@"Date is earlier than previous fuel date of %@", lastDate]];
			return;
		}
	}
	Gas *nextPump = [appDelegate findNextGasEntry:dateValue odometer:distance];
	if (nextPump && (gas.pk == -1 || gas.pk != nextPump.pk)) { 
		if (distance > nextPump.odometer) {
			[errorText setText:[NSString stringWithFormat:@"Odometer is higher than next value of %.1f", lastPump.odometer]];
			return;
		} else if ([dateValue compare:nextPump.date] == NSOrderedDescending) {
			NSDateFormatter *formatter = [FuelLogAppDelegate pref].dateFormatter;
			NSString *nextDate = [formatter stringFromDate:nextPump.date];
			[errorText setText:[NSString stringWithFormat:@"Date is later than next fuel date of %@", nextDate]];
			return;
		}
	}
	[errorText setText:@""];
	[gas setDate:dateValue];
	[gas setOdometer:distance];
	[gas setVolume:fuel];
	[gas setCost:cost];
	[gas setFull:fullTankSwitch.on]; 
	[appDelegate addGasIfNeeded:gas previous:lastPump next:nextPump];
	[gas release];
	[odometerBox resignFirstResponder];
	[fuelBox resignFirstResponder];
	[costBox resignFirstResponder];
	[self dismissModalViewControllerAnimated:YES];
}

- (IBAction)cancel:(id)sender {
	[errorText setText:@""];
	[gas release];
	[odometerBox resignFirstResponder];
	[fuelBox resignFirstResponder];
	[costBox resignFirstResponder];
	[self dismissModalViewControllerAnimated:YES];
}

- (IBAction)deleteEntry:(id)sender {
	[self alertDeleteCancelAction];
}

- (IBAction)editDate:(id)sender {
	DateViewController *dateController = [FuelLogViewController dateViewController];
	[dateController setEditedObject:self];
	[dateController setEditedFieldKey:@"dateValue"];
	[dateController setText:(NSLocalizedString(@"GasView datesubscreen",@"Date"))]; 
	[dateController setDateValue:dateValue];
	[self presentModalViewController:dateController animated:YES];
}

- (void)updateDpf {
	FuelLogAppDelegate *appDelegate = (FuelLogAppDelegate *)[[UIApplication sharedApplication] delegate];
	float odometer = [FuelLogAppDelegate scanFloat:odometerBox.text];
	float fuel = [FuelLogAppDelegate scanFloat:fuelBox.text];
	float dpf = [appDelegate gasEconomy:gas.pk odometer:odometer fuel:fuel];
	int prefUnits = [FuelLogAppDelegate pref].units;
	if (dpf > 0.0 &&  prefUnits == INV_METRIC) {
		dpf = 100.0 / dpf;
	} else if (dpf > 0.0 && prefUnits == NORWAY) {
		dpf = 10.0 / dpf;
	} else if (prefUnits == UK) {
		dpf = dpf * UK_GALLON;
	}
	[dpfText setText:[[FuelLogAppDelegate pref].volumeFormatter stringFromNumber:[NSNumber numberWithFloat:dpf]]];
}

- (void)updateUnitCost {
	float v = [FuelLogAppDelegate scanFloat:fuelBox.text];
	if (v > 0.0) {
		float c = [FuelLogAppDelegate scanFloat:costBox.text];
		float uc = c/v;
		NSNumberFormatter *unitCostFormatter = [FuelLogAppDelegate pref].unitCostFormatter;
		[unitCostText setText:[unitCostFormatter stringFromNumber:[NSNumber numberWithFloat:uc]]];
	} else if ([FuelLogAppDelegate scanFloat:unitCostText.text] != 0.0) {
		[unitCostText setText:@"0"];
	}
}
#pragma mark -
- (BOOL)textFieldShouldReturn:(UITextField *)theTextField {
	[errorText setText:@""];
	float val = [FuelLogAppDelegate scanFloat:theTextField.text];
	if (val == 0) {
		theTextField.text = @"";
		return NO;
	}
	[theTextField resignFirstResponder];
	if (theTextField == odometerBox) {
//		gas.odometer = val;
		odometerBox.text = [[FuelLogAppDelegate pref].distanceFormatter stringFromNumber:[NSNumber numberWithFloat:val]];
		odometerBox.clearsOnBeginEditing = FALSE;
	} else if (theTextField == fuelBox) {
//		gas.volume = val;
		fuelBox.text = [[FuelLogAppDelegate pref].volumeFormatter stringFromNumber:[NSNumber numberWithFloat:val]];
		[self updateUnitCost];
		fuelBox.clearsOnBeginEditing = FALSE;
	} else if (theTextField == costBox) {
//		gas.cost = val;
		costBox.text = [[FuelLogAppDelegate pref].costFormatter stringFromNumber:[NSNumber numberWithFloat:val]];
		[self updateUnitCost];
		costBox.clearsOnBeginEditing = FALSE;
	}
	return YES;
}

- (void)textFieldDidEndEditing:(UITextField *)theTextField {
	if (theTextField == odometerBox) {
		 odometerBox.clearsOnBeginEditing = FALSE;
	} else if (theTextField == fuelBox) {
		 fuelBox.clearsOnBeginEditing = FALSE;
	} else if (theTextField == costBox) {
		 costBox.clearsOnBeginEditing = FALSE;
	}
	
}

-(BOOL) textField:(UITextField*)textField shouldChangeCharactersInRange:(NSRange)range 
replacementString:(NSString*)textEntered {
	//	debug(@"in shouldChangeCharactersInRange");
	NSCharacterSet * myCharSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789,."];
	for (int i = 0; i < [textEntered length]; i++) 
	{
		unichar c = [textEntered characterAtIndex:i];
		if (![myCharSet characterIsMember:c]) 	return NO;
	} 
	return YES;
}	

#pragma mark -


- (IBAction)odometerChanged:(id)sender {
	[self updateDpf];
}

- (IBAction)fuelChanged:(id)sender {
	[self updateDpf];
	[self updateUnitCost];
}

- (IBAction)costChanged:(id)sender {
	[self updateUnitCost];
}

- (void)setBoxes {
	FuelLogAppDelegate *appDelegate = (FuelLogAppDelegate *)[[UIApplication sharedApplication] delegate];
	if (appDelegate.currentCar) {
//		[carLabel setText:appDelegate.currentCar.label];
		self.navItem.title = appDelegate.currentCar.label;
	}
	NSDateFormatter *formatter = [FuelLogAppDelegate pref].dateFormatter;
	NSString *title = [formatter stringFromDate:dateValue];
	[dateButton setTitle:title forState:UIControlStateNormal];
	[dateButton setTitle:title forState:UIControlStateHighlighted];
	[dateButton setTitle:title forState:UIControlStateSelected];
	odometerBox.text = [[FuelLogAppDelegate pref].distanceFormatter stringFromNumber:[NSNumber numberWithFloat:gas.odometer]];
	[fuelLabel setText:[FuelLogAppDelegate pref].fuelText];
	fuelBox.text = [[FuelLogAppDelegate pref].volumeFormatter stringFromNumber:[NSNumber numberWithFloat:gas.volume]];
	[dpfLabel setText:[FuelLogAppDelegate pref].dpfText];
	[self updateDpf];
	costBox.text = [[FuelLogAppDelegate pref].costFormatter stringFromNumber:[NSNumber numberWithFloat:gas.cost]];
	[self updateUnitCost];
	fullTankSwitch.on = gas.full;
	[errorText setText:@""];
	if (gas.pk == -1) {
		deleteButton.hidden = YES;
		odometerBox.clearsOnBeginEditing = TRUE;
		fuelBox.clearsOnBeginEditing = TRUE;
		costBox.clearsOnBeginEditing = TRUE;
	} else {
		deleteButton.hidden = NO;
		odometerBox.clearsOnBeginEditing = FALSE;
		fuelBox.clearsOnBeginEditing = FALSE;
		costBox.clearsOnBeginEditing = FALSE;
	}
//	versionLabel.text = [@"Ver. 3.4 Build: " stringByAppendingString:kBuildNumber];
}

@end
